package com.zenithmind.task.controller;

import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import com.zenithmind.task.pojo.entity.TaskTemplate;
import com.zenithmind.task.pojo.query.TaskTemplateQuery;
import com.zenithmind.task.pojo.vo.TaskTemplateVO;
import com.zenithmind.task.service.TaskTemplateService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 任务模板管理控制器
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/zenithMind/task-template")
@RequiredArgsConstructor
@Tag(name = "任务模板管理", description = "任务模板的创建、查询、更新、删除等功能")
public class TaskTemplateController {

    private final TaskTemplateService taskTemplateService;

    // ==================== 基础CRUD操作 ====================

    @GetMapping("/page")
    @Operation(summary = "分页查询任务模板列表", description = "支持多条件筛选的任务模板分页查询")
    public Result<PageResult<TaskTemplateVO>> getTaskTemplatePage(TaskTemplateQuery query) {
        String userId = UserContext.requireUserId();
        PageResult<TaskTemplateVO> result = taskTemplateService.getTaskTemplatePage(query, userId);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "查询任务模板详情", description = "根据ID查询任务模板的详细信息")
    public Result<TaskTemplateVO> getTaskTemplateById(@Parameter(description = "模板ID") @PathVariable String id) {
        String userId = UserContext.requireUserId();
        TaskTemplateVO taskTemplate = taskTemplateService.getTaskTemplateById(id, userId);
        return Result.success(taskTemplate);
    }

    @PostMapping
    @Operation(summary = "创建任务模板", description = "创建新的任务模板")
    public Result<Boolean> createTaskTemplate(@Valid @RequestBody TaskTemplate taskTemplate) {
        String userId = UserContext.requireUserId();
        Boolean result = taskTemplateService.createTaskTemplate(taskTemplate, userId);
        return Result.success(result);
    }

    @PutMapping
    @Operation(summary = "更新任务模板", description = "更新任务模板信息")
    public Result<Boolean> updateTaskTemplate(@Valid @RequestBody TaskTemplate taskTemplate) {
        String userId = UserContext.requireUserId();
        Boolean result = taskTemplateService.updateTaskTemplate(taskTemplate, userId);
        return Result.success(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除任务模板", description = "删除指定的任务模板")
    public Result<Boolean> deleteTaskTemplate(@Parameter(description = "模板ID") @PathVariable String id) {
        String userId = UserContext.requireUserId();
        Boolean result = taskTemplateService.deleteTaskTemplate(id, userId);
        return Result.success(result);
    }

    @DeleteMapping("/batch")
    @Operation(summary = "批量删除任务模板", description = "批量删除多个任务模板")
    public Result<Boolean> batchDeleteTaskTemplates(@RequestBody List<String> ids) {
        String userId = UserContext.requireUserId();
        Boolean result = taskTemplateService.batchDeleteTaskTemplates(ids, userId);
        return Result.success(result);
    }

    // ==================== 模板操作 ====================

    @PostMapping("/create-from-task")
    @Operation(summary = "从任务创建模板", description = "基于现有任务创建模板")
    public Result<Boolean> createTemplateFromTask(
            @Parameter(description = "任务ID") @RequestParam String taskId,
            @Parameter(description = "模板名称") @RequestParam String templateName,
            @Parameter(description = "模板描述") @RequestParam(required = false) String templateDescription) {
        String userId = UserContext.requireUserId();
        Boolean result = taskTemplateService.createTemplateFromTask(taskId, templateName, templateDescription, userId);
        return Result.success(result);
    }

    @PostMapping("/create-task")
    @Operation(summary = "从模板创建任务", description = "基于模板创建新任务")
    public Result<Boolean> createTaskFromTemplate(
            @Parameter(description = "模板ID") @RequestParam String templateId,
            @Parameter(description = "自定义数据") @RequestBody(required = false) Map<String, Object> customData) {
        String userId = UserContext.requireUserId();
        Boolean result = taskTemplateService.createTaskFromTemplate(templateId, customData, userId);
        return Result.success(result);
    }

    @PostMapping("/copy")
    @Operation(summary = "复制模板", description = "复制现有模板创建新模板")
    public Result<Boolean> copyTemplate(
            @Parameter(description = "模板ID") @RequestParam String templateId,
            @Parameter(description = "新模板名称") @RequestParam String newTemplateName) {
        String userId = UserContext.requireUserId();
        Boolean result = taskTemplateService.copyTemplate(templateId, newTemplateName, userId);
        return Result.success(result);
    }

    @PutMapping("/{id}/public")
    @Operation(summary = "设置模板公开性", description = "设置模板为公共或私有")
    public Result<Boolean> setTemplatePublic(
            @Parameter(description = "模板ID") @PathVariable String id,
            @Parameter(description = "是否公共") @RequestParam Boolean isPublic) {
        String userId = UserContext.requireUserId();
        Boolean result = taskTemplateService.setTemplatePublic(id, isPublic, userId);
        return Result.success(result);
    }

    // ==================== 模板查询方法 ====================

    @GetMapping("/public")
    @Operation(summary = "查询公共模板", description = "查询所有公共可用的模板")
    public Result<List<TaskTemplateVO>> getPublicTemplates() {
        String userId = UserContext.requireUserId();
        List<TaskTemplateVO> result = taskTemplateService.getPublicTemplates(userId);
        return Result.success(result);
    }

    @GetMapping("/my")
    @Operation(summary = "查询我创建的模板", description = "查询当前用户创建的所有模板")
    public Result<List<TaskTemplateVO>> getMyCreatedTemplates() {
        String userId = UserContext.requireUserId();
        List<TaskTemplateVO> result = taskTemplateService.getUserCreatedTemplates(userId);
        return Result.success(result);
    }

    @GetMapping("/popular")
    @Operation(summary = "查询热门模板", description = "查询使用频率最高的模板")
    public Result<List<TaskTemplateVO>> getPopularTemplates(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        String userId = UserContext.requireUserId();
        List<TaskTemplateVO> result = taskTemplateService.getPopularTemplates(limit, userId);
        return Result.success(result);
    }

    @GetMapping("/search")
    @Operation(summary = "搜索模板", description = "根据关键词搜索模板")
    public Result<List<TaskTemplateVO>> searchTemplates(
            @Parameter(description = "搜索关键词") @RequestParam String keyword) {
        String userId = UserContext.requireUserId();
        List<TaskTemplateVO> result = taskTemplateService.searchTemplates(keyword, userId);
        return Result.success(result);
    }

    @GetMapping("/statistics")
    @Operation(summary = "获取模板统计信息", description = "获取模板的使用统计信息")
    public Result<Object> getTemplateStatistics() {
        String userId = UserContext.requireUserId();
        
        List<TaskTemplateVO> publicTemplates = taskTemplateService.getPublicTemplates(userId);
        List<TaskTemplateVO> myTemplates = taskTemplateService.getUserCreatedTemplates(userId);
        List<TaskTemplateVO> popularTemplates = taskTemplateService.getPopularTemplates(5, userId);
        
        return Result.success(Map.of(
            "publicTemplateCount", publicTemplates.size(),
            "myTemplateCount", myTemplates.size(),
            "popularTemplates", popularTemplates,
            "myTemplates", myTemplates
        ));
    }

    @GetMapping("/categories")
    @Operation(summary = "获取模板分类", description = "获取所有模板分类信息")
    public Result<Object> getTemplateCategories() {
        String userId = UserContext.requireUserId();
        
        // TODO: 实现模板分类统计
        
        return Result.success("模板分类功能待实现");
    }

    @GetMapping("/recommendations")
    @Operation(summary = "获取推荐模板", description = "根据用户使用习惯推荐模板")
    public Result<List<TaskTemplateVO>> getRecommendedTemplates(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "5") Integer limit) {
        String userId = UserContext.requireUserId();
        
        // 简单实现：返回热门模板作为推荐
        List<TaskTemplateVO> result = taskTemplateService.getPopularTemplates(limit, userId);
        return Result.success(result);
    }
}
